package org.example.readObject;

import java.io.*;

public class EvilSerializationDemo {
    public static void main(String[] args) {
        // 创建一个恶意对象（现实中可能来自网络）
        EvilObject evil = new EvilObject("calc.exe"); // 打开计算器

        // 序列化恶意对象到字节数组
        byte[] serializedData = serialize(evil);

        // 反序列化（触发攻击）
        deserialize(serializedData);
    }

    private static byte[] serialize(Serializable obj) {
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
             ObjectOutputStream oos = new ObjectOutputStream(baos)) {
            oos.writeObject(obj);
            return baos.toByteArray();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private static void deserialize(byte[] data) {
        try (ByteArrayInputStream bais = new ByteArrayInputStream(data);
             ObjectInputStream ois = new ObjectInputStream(bais)) {
            ois.readObject(); // ⚠️ 这里会触发恶意代码！
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}